package cytj.setup.fragment;


import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import cytj.setup.R;
import cytj.setup.activity.SetupActivity;
import cytj.setup.base.MyAPP;
import cytj.setup.util.CharacterTool;

/**
 * 基站配置的Fragment隶属于SetupActivity
 * Created by LTP on 2015/12/21
 */
public class BaseSetupFragment extends Fragment implements View.OnClickListener {
    /**
     * BaseSetupFragment的视图
     */
    private View view;
    /**
     * 基站ID/显示基站ID/基站IP/基站端口/基站载波频率/目标IP/目标端口/网关IP 的编辑框
     */
    private EditText editText_baseID, editText_showBaseID, editText_baseIP, editText_baseCom, editText_frequency, editText_targetIP, editText_targetCom, editText_gatewayIP;
    /**
     * 基站类型/协议类型 的下拉框
     */
    private Spinner spinner_baseType, spinner_treaty;
    /**
     * 调试用TAG
     */
    private static final String TAG = "LTP";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_base_setup, container, false);
        initView();
        return view;
    }

    /**
     * 控件初始化
     */
    private void initView() {
        editText_baseID = (EditText) view.findViewById(R.id.editText_baseID_baseSetupFragment);
        editText_showBaseID = (EditText) view.findViewById(R.id.editText_showBaseID_baseSetupFragment);
        spinner_baseType = (Spinner) view.findViewById(R.id.spinner_baseType_baseSetupFragment);
        editText_baseIP = (EditText) view.findViewById(R.id.editText_baseIP_baseSetupFragment);
        editText_baseCom = (EditText) view.findViewById(R.id.editText_baseCom_baseSetupFragment);
        editText_baseCom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals("") && Integer.parseInt(s.toString()) > 65535) {
                    // 基站端口用2个字节表示，禁止用户输入大于65535的数
                    Toast.makeText(getActivity(), "请输入小于65535的数！", Toast.LENGTH_SHORT).show();
                    editText_baseCom.setText(s.subSequence(0, s.length() - 1));
                    editText_baseCom.setSelection(s.length() - 1);
                }
            }
        });
        editText_frequency = (EditText) view.findViewById(R.id.editText_frequency_baseSetupFragment);
        editText_targetIP = (EditText) view.findViewById(R.id.editText_targetIP_baseSetupFragment);
        editText_targetCom = (EditText) view.findViewById(R.id.editText_targetCom_baseSetupFragment);
        editText_targetCom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 目标端口用2个字节表示，禁止用户输入大于65535的数
                if (!s.toString().equals("") && Integer.parseInt(s.toString()) > 65535) {
                    Toast.makeText(getActivity(), "请输入小于65535的数！", Toast.LENGTH_SHORT).show();
                    editText_targetCom.setText(s.subSequence(0, s.length() - 1));
                    editText_targetCom.setSelection(s.length() - 1);
                }
            }
        });
        editText_gatewayIP = (EditText) view.findViewById(R.id.editText_gatewayIP_baseSetupFragment);
        spinner_treaty = (Spinner) view.findViewById(R.id.spinner_treaty_baseSetupFragment);
        // 基站配置 读/写 的按键
        view.findViewById(R.id.button_read_baseSetupFragment).setOnClickListener(this);
        view.findViewById(R.id.button_write_baseSetupFragment).setOnClickListener(this);
        view.findViewById(R.id.relativeLayout_baseSetupFragment).setOnClickListener(this);
    }

    /**
     * 根据基站类型获取基站类型码
     *
     * @param baseType 01-运行基站，02-中继，04部署基站，00-保持不变
     */
    private String getBaseType(String baseType) {
        String baseTypeCode = "01";
        switch (baseType) {
            case "运行基站":
                baseTypeCode = "01";
                break;
            case "中继":
                baseTypeCode = "02";
                break;
            case "部署基站":
                baseTypeCode = "04";
                break;
            case "保持不变":
                baseTypeCode = "00";
                break;
        }
        return baseTypeCode;
    }

    /**
     * 根据基站类型码选择基站类型
     *
     * @param baseType 01-运行基站，02-中继，04部署基站，00-保持不变
     */
    public void setBaseType(String baseType) {
        switch (baseType) {
            case "01":
                spinner_baseType.setSelection(0);
                break;
            case "02":
                spinner_baseType.setSelection(1);
                break;
            case "04":
                spinner_baseType.setSelection(2);
                break;
            case "00":
                spinner_baseType.setSelection(3);
                break;
        }
    }

    /**
     * 根据协议类型获取协议类型码
     *
     * @param treaty 协议类型：00-UDP, 01-TCP Client, 02-UDP Server, 03-TCP Server
     */

    private String getTreaty(String treaty) {
        String treatyCode = "00";
        switch (treaty) {
            case "UDP":
                treatyCode = "00";
                break;
            case "TCP Client":
                treatyCode = "01";
                break;
            case "UDP Server":
                treatyCode = "02";
                break;
            case "TCP Server":
                treatyCode = "03";
                break;
        }
        return treatyCode;
    }

    /**
     * 根据协议类型码选择协议类型
     *
     * @param treaty 协议类型：00-UDP, 01-TCP Client, 02-UDP Server, 03-TCP Server
     */
    public void setTreaty(String treaty) {
        switch (treaty) {
            case "00":
                spinner_treaty.setSelection(0);
                break;
            case "01":
                spinner_treaty.setSelection(1);
                break;
            case "02":
                spinner_treaty.setSelection(2);
                break;
            case "03":
                spinner_treaty.setSelection(3);
                break;
        }
    }

    public void setBaseIPText(String baseIPText) {
        editText_baseIP.setText(baseIPText);
    }

    public void setBaseComText(String baseComText) {
        editText_baseCom.setText(baseComText);
    }

    public void setFrequencyText(String frequency) {
        editText_frequency.setText(frequency);
    }

    public void setTargetIPText(String targetIP) {
        editText_targetIP.setText(targetIP);
    }

    public void setTargetComText(String targetCom) {
        editText_targetCom.setText(targetCom);
    }

    public void setGatewayIPText(String gatewayIP) {
        editText_gatewayIP.setText(gatewayIP);
    }

    public void setEditText_showBaseID(String showBaseID) {
        editText_showBaseID.setText(showBaseID);
    }

    @Override
    public void onClick(View v) {
        String baseID = editText_baseID.getText().toString();
        switch (v.getId()) {
            case R.id.button_read_baseSetupFragment:
                // 点击基站配置的读取按键
                editText_showBaseID.setText("");
                if (!MyAPP.getMyAPPInstance().isBluetoothConnected()) {
                    Toast.makeText(getActivity(), "请先连接蓝牙！", Toast.LENGTH_SHORT).show();
                } else {
                    if (baseID.length() != 6) {
                        Toast.makeText(getActivity(), "基站编码错误！", Toast.LENGTH_SHORT).show();
                    } else {
                        String protocol = "ABAB" + baseID + "DE050000" + baseID;
                        String xorString = CharacterTool.xor(CharacterTool.hexStringToBytes(protocol), CharacterTool.hexStringToBytes(protocol).length);
                        protocol = protocol.substring(0, 14) + xorString + protocol.substring(14);
                        Log.d(TAG, "发送读取基站配置的协议：" + CharacterTool.splitData(protocol));
                        byte[] bytes = CharacterTool.hexStringToBytes(protocol);
                        ((SetupActivity) getActivity()).bluetoothService.write(bytes);
                        ((SetupActivity) getActivity()).showProgressDialog("操作中，请稍候... ");
                        baseSetupCountDownTimer.start();
                    }
                }
                break;
            case R.id.button_write_baseSetupFragment:
                // 点击基站配置的写入按键
                if (!MyAPP.getMyAPPInstance().isBluetoothConnected()) {
                    Toast.makeText(getActivity(), "请先连接蓝牙！", Toast.LENGTH_SHORT).show();
                } else {
                    if (baseID.length() != 6) {
                        Toast.makeText(getActivity(), "基站编码错误！", Toast.LENGTH_SHORT).show();
                    } else {
                        String protocol = getProtocol(baseID);
                        Log.d(TAG, "发送写入基站配置的协议：" + CharacterTool.splitData(protocol));
                        if (!TextUtils.isEmpty(protocol)) {
                            byte[] bytes = CharacterTool.hexStringToBytes(protocol);
                            ((SetupActivity) getActivity()).bluetoothService.write(bytes);
                            ((SetupActivity) getActivity()).showProgressDialog("操作中，请稍候... ");
                            baseSetupCountDownTimer.start();
                        }
                    }
                }
                break;
            case R.id.relativeLayout_baseSetupFragment:
                //点击EditText外部隐藏键盘
                InputMethodManager imm = (InputMethodManager)
                        getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
        }
    }

    /**
     * 获取发送的协议
     *
     * @param baseID 基站的ID
     * @return 要发送的协议
     */
    private String getProtocol(String baseID) {
        String baseType = getBaseType(spinner_baseType.getSelectedItem().toString().trim());
        String frequency = editText_frequency.getText().toString();
        String targetIP = editText_targetIP.getText().toString();
        String targetCom = editText_targetCom.getText().toString();
        String baseIP = editText_baseIP.getText().toString();
        String baseCom = editText_baseCom.getText().toString();
        String gatewayIP = editText_gatewayIP.getText().toString();
        if (TextUtils.isEmpty(frequency) || TextUtils.isEmpty(targetIP) || TextUtils.isEmpty(targetCom) || TextUtils.isEmpty(baseIP) || TextUtils.isEmpty(baseCom) || TextUtils.isEmpty(gatewayIP)) {
            Toast.makeText(getActivity(), "请将配置填写完整！", Toast.LENGTH_SHORT).show();
            return "";
        } else {
            String protocol = "ABAB" + baseID + "DF1B0000" + baseID + baseType;
            frequency = CharacterTool.intToHexString(frequency, 3);
            targetIP = CharacterTool.parseIP(targetIP);
            targetCom = CharacterTool.intToHexString(targetCom, 2);
            baseIP = CharacterTool.parseIP(baseIP);
            baseCom = CharacterTool.intToHexString(baseCom, 2);
            gatewayIP = CharacterTool.parseIP(gatewayIP);
            String treaty = getTreaty(spinner_treaty.getSelectedItem().toString().trim());
            protocol += frequency + "00" + targetIP + targetCom + baseIP + baseCom + gatewayIP + treaty;
            String xorString = CharacterTool.xor(CharacterTool.hexStringToBytes(protocol), CharacterTool.hexStringToBytes(protocol).length);
            protocol = protocol.substring(0, 16) + xorString + protocol.substring(16);
            return protocol;
        }
    }

    /**
     * 读取/写入按键按下后倒计时10秒
     */
    public CountDownTimer baseSetupCountDownTimer = new CountDownTimer(11000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            ((SetupActivity) getActivity()).progressDialog.setMessage("操作中，请稍候... " + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
            Toast.makeText(getActivity(), "超时,操作失败", Toast.LENGTH_SHORT).show();
            if (((SetupActivity) getActivity()).progressDialog != null) {
                ((SetupActivity) getActivity()).progressDialog.dismiss();
            }
        }
    };
}
